<template>
	<!-- 新增任务弹窗 -->
	<uni-popup ref="taskPopup" type="center">
		<view class="task-popup-content">
			<!-- 弹窗标题区域 -->
			<view class="task-popup-header">
				<view class="header-icon">{{ isEditMode ? '✏️' : '➕' }}</view>
				<text class="task-popup-title">{{ isEditMode ? '编辑任务' : '添加任务' }}</text>
				<text class="task-popup-subtitle">{{ isEditMode ? '修改任务信息' : '创建新的任务' }}</text>
			</view>
			
			<!-- 表单区域 -->
			<view class="task-popup-body">
				<uni-forms :model="newTask" ref="taskRef" :rules="rules" class="task-form">
					<!-- 任务名称 -->
					<uni-forms-item label="任务名称" label-width="100px" required name="taskName" class="form-item">
						<uni-easyinput v-model="newTask.taskName" placeholder="请输入任务名称" clearable maxlength="15" 
							class="custom-input" />
					</uni-forms-item>
					
					<!-- 任务图标 -->
					<uni-forms-item label="任务图标" label-width="100px" required name="icon" class="form-item">
						<uni-file-picker limit="1" :del-icon="false" :disable-preview="true" :imageStyles="imageStyles"
							:auto-upload="false" file-extname="png,jpg" v-model="taskIcon" file-mediatype="image"
							@select="handleIconSelect">
						</uni-file-picker>
					</uni-forms-item>
					
					<!-- 任务标签 -->
					<uni-forms-item label="任务标签" label-width="100px" required name="tags" class="form-item">
						<uni-data-checkbox v-model="newTask.tags" :localdata="tagOptions" :multiple="false"
							check-strictly class="custom-checkbox"></uni-data-checkbox>
					</uni-forms-item>
					
					<!-- 任务分数 -->
					<uni-forms-item label="⭐分数" label-width="100px" required name="score" class="form-item">
						<uni-number-box v-model="newTask.score" placeholder="请输入任务分数" :min="1" :max="100" 
							class="custom-number-box" />
					</uni-forms-item>
				</uni-forms>
				
				<!-- 按钮区域 -->
				<view class="task-popup-footer">
					<button class="task-cancel-button" @click="handleClosePopup" hover-class="button-hover">
						<text class="button-text">取消</text>
					</button>
					<button class="task-confirm-button" @click="handleSubmitNewTask" :loading="loading" 
						hover-class="button-hover">
						<text class="button-text">{{ isEditMode ? '更新' : '创建' }}</text>
					</button>
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup lang="ts">
	import { ref, computed } from 'vue';
	import { addTaskAPI, updateTaskAPI } from '@/services/task';
	import { uploadAvatarAPI } from '@/services/user';
	import { TaskItem, AvatarUploadResult } from '@/types';
	import { baseURL } from '@/utils/config';
	import { FileType } from '@/types';
	import { getThemeStyles } from '@/stores/theme';
	// 定义事件
	const emit = defineEmits<{
		taskAdded : [];
	}>();

	// 新增任务弹窗引用
	const taskPopup = ref(null);
	// 表单引用
	const taskRef = ref(null);

	// 加载状态，用于防重复点击
	const loading = ref(false);

	// 是否为编辑模式
	const isEditMode = ref(false);

	// 当前编辑的任务ID
	const editingTaskId = ref<number | null>(null);

	// 新任务数据 TaskItem类型
	const newTask = ref<TaskItem>({
		taskName: '',
		icon: '',
		score: 1,
		tags: '学习',
		status: 0
	});

	// 任务图标上传临时数据
	const taskIcon = ref<FileType[]>([]);

	// 图片样式配置
	const imageStyles = ref({
		width: '180rpx',
		height: '180rpx',
		border: { // 如果为 Boolean 值，可以控制边框显示与否
			"color": "#eee",		// 边框颜色
			"width": "1px",		// 边框宽度
			"style": "solid",	 // 边框样式
			"radius": "50%" 		// 边框圆角，支持百分比
		}
	});

	// 标签选择数据
	const tagOptions = ref([
		{ value: '学习', text: '学习' },
		{ value: '家务', text: '家务' }
	]);

	/**
	 * 获取当前主题样式
	 */
	const themeStyles = computed(() => getThemeStyles());

	// 表单验证规则
	const rules = ref({
		taskName: {
			rules: [{
				required: true,
				message: '请输入任务名称'
			}]
		},
		icon: {
			rules: [{
				required: true,
				message: '请选择任务图标'
			}]
		},
		tags: {
			rules: [{
				required: true,
				message: '请选择任务标签'
			}]
		},
		score: {
			rules: [{
				required: true,
				message: '请输入任务分数'
			}]
		}
	});




	/**
	 * 打开弹窗
	 */
	const addTask = () => {
		// 重置表单
		resetForm();
		// 设置为添加模式
		isEditMode.value = false;
		editingTaskId.value = null;

		// 打开弹窗
		taskPopup.value.open();
		//关闭之前校验的报错提示
		taskRef.value.clearValidate();
	};

	/**
	 * 编辑任务
	 * @param task 要编辑的任务数据
	 */
	const editTask = (task : TaskItem) => {
		console.log("task", task)
		// 设置为编辑模式
		isEditMode.value = true;
		editingTaskId.value = task.id || null;

		// 填充表单数据
		newTask.value = {
			...task,
			tags: task.tags || '学习'
		};

		// 正确设置taskIcon，确保组件能显示编辑任务的图标
		if (task.icon) {
			taskIcon.value = [{
				url: baseURL + task.icon,
				extname: task.icon.split('.').pop() || '',
				name: task.icon.split('/').pop() || 'task_icon'
			}];
			console.log("taskIcon.value", taskIcon.value);
		} else {
			taskIcon.value = [];
		}


		// 打开弹窗
		taskPopup.value.open();
		// 清除之前的校验提示
		taskRef.value.clearValidate();
	};
	/**
	 * 重置表单
	 */
	const resetForm = () => {
		newTask.value = {
			taskName: '',
			icon: '',
			score: 1,
			tags: '学习',
			status: 0
		};
		taskIcon.value = [];
	};

	/**
		 * 处理图标选择
		 * @param {any} file 选择的文件信息
		 */
	const handleIconSelect = (file) => {
		console.log('选择的图标文件:', file);
		// 检查是否有选择文件
		if (file && file.tempFiles && file.tempFiles.length > 0) {
			// 调用上传函数
			uploadAvatarAPI(file.tempFiles[0]).then(response => {
				handleIconUploadSuccess(response);
			}).catch(error => {
				handleIconUploadFail(error);
			});
		}
	};

	/**
		 * 处理图标上传成功
		 * @param {AvatarUploadResult} response 上传成功的响应信息
		 */
	const handleIconUploadSuccess = (response : AvatarUploadResult) => {
		console.log('图标上传成功:', response);
		try {
			// 更新图标URL到newTask.icon
			if (response && response.url) {
				newTask.value.icon = response.url;

				// 同时更新taskIcon，确保组件能正确显示图片
				taskIcon.value = [{
					url: baseURL + response.url,
					extname: response.url.split('.').pop() || '',
					name: response.url.split('/').pop() || 'task_icon'
				}];

				// 显示成功提示
				uni.showToast({
					title: '图标上传成功',
					icon: 'success'
				});
			} else {
				throw new Error('响应数据格式不正确');
			}
		} catch (error) {
			console.error('处理上传成功响应失败:', error);
			handleIconUploadFail(error);
		}
	};

	/**
		 * 处理图标上传失败
		 * @param {any} error 上传失败的错误信息
		 */
	const handleIconUploadFail = (error) => {
		console.error('图标上传失败:', error);
		uni.showToast({
			title: '图标上传失败，请重试',
			icon: 'none'
		});
		taskIcon.value = [];
	};

	/**
	 * 关闭弹窗
	 */
	const handleClosePopup = () => {
		taskPopup.value.close();
	};


	/**
	 * 提交新任务
	 */
	const handleSubmitNewTask = async () => {
		// 防止重复点击
		if (loading.value) {
			return;
		}

		try {
			// 设置加载状态
			loading.value = true;

			// 验证表单
			await taskRef.value.validate();

			// 确保图标已经上传
			if (!newTask.value.icon) {
				uni.showToast({
					title: '请先上传任务图标',
					icon: 'none'
				});
				return;
			}

			// 根据模式决定调用添加还是更新API
			if (isEditMode.value && editingTaskId.value) {
				// 更新任务
				await updateTaskAPI(newTask.value);
				uni.showToast({
					title: '任务更新成功',
					icon: 'success'
				});
			} else {
				// 添加任务
				await addTaskAPI(newTask.value);
				uni.showToast({
					title: '任务添加成功',
					icon: 'success'
				});
			}

			// 触发任务添加成功事件，通知父组件刷新列表
			emit('taskAdded');

			// 关闭弹窗
			handleClosePopup();
		} catch (error) {
			console.error(isEditMode.value ? '更新任务失败:' : '添加任务失败:', error);
			// 其他错误
			uni.showToast({
				title: isEditMode.value ? '更新任务失败' : '添加任务失败',
				icon: 'none'
			});
		} finally {
			// 无论成功失败，都重置加载状态
			loading.value = false;
		}
	};

	// 暴露方法给父组件
	defineExpose({
		addTask,
		handleClosePopup,
		editTask
	});
</script>

<style lang="scss">
	/**
	 * 任务弹窗容器
	 */
	.task-popup-content {
		width: 90vw;
		max-width: 600rpx;
		background: v-bind('themeStyles.bgCard');
		border-radius: 24rpx;
		overflow: hidden;
		position: relative;
		z-index: 1000;
		box-sizing: border-box;
		box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.15);
		border: 1rpx solid v-bind('themeStyles.borderLight');
		animation: popupFadeIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	}

	@keyframes popupFadeIn {
		from {
			opacity: 0;
			transform: scale(0.9) translateY(-20rpx);
		}
		to {
			opacity: 1;
			transform: scale(1) translateY(0);
		}
	}

	/**
	 * 弹窗标题区域
	 */
	.task-popup-header {
		padding: 48rpx 32rpx 32rpx;
		text-align: center;
		background: v-bind('themeStyles.primaryGradient');
		position: relative;
		overflow: hidden;

		&::before {
			content: '';
			position: absolute;
			top: -50%;
			left: -50%;
			width: 200%;
			height: 200%;
			background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
			animation: headerShine 3s linear infinite;
		}
	}

	@keyframes headerShine {
		0% {
			transform: translate(-50%, -50%) rotate(0deg);
		}
		100% {
			transform: translate(-50%, -50%) rotate(360deg);
		}
	}

	.header-icon {
		font-size: 56rpx;
		margin-bottom: 16rpx;
		animation: iconBounce 0.6s ease-out;
	}

	@keyframes iconBounce {
		0%, 100% {
			transform: scale(1);
		}
		50% {
			transform: scale(1.2);
		}
	}

	.task-popup-title {
		display: block;
		font-size: 36rpx;
		font-weight: 700;
		color: white;
		margin-bottom: 8rpx;
		letter-spacing: 1rpx;
	}

	.task-popup-subtitle {
		display: block;
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.9);
		font-weight: 400;
	}

	/**
	 * 表单区域
	 */
	.task-popup-body {
		padding: 32rpx;
		width: 100%;
		max-width: 100%;
		box-sizing: border-box;
		overflow: hidden;
		background: v-bind('themeStyles.bgCard');
	}

	.task-form {
		animation: formSlideIn 0.4s ease-out 0.1s both;
	}

	@keyframes formSlideIn {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	/**
	 * 表单项样式
	 */
	.form-item {
		margin-bottom: 28rpx;

		:deep(.uni-forms-item__label) {
			font-size: 28rpx;
			font-weight: 600;
			color: v-bind('themeStyles.textPrimary');
			margin-bottom: 12rpx;
		}

		:deep(.uni-forms-item__content) {
			background: v-bind('themeStyles.bgSecondary');
			border-radius: 12rpx;
			border: 1rpx solid v-bind('themeStyles.borderLight');
			padding: 8rpx 12rpx;
			transition: all 0.3s ease;

			&:focus-within {
				border-color: v-bind('themeStyles.primaryColor');
				box-shadow: 0 0 0 3rpx v-bind('themeStyles.accentBg');
			}
		}
	}

	/**
	 * 输入框样式
	 */
	:deep(.custom-input) {
		.uni-easyinput__content {
			background: transparent !important;
			border: none !important;
		}

		.uni-easyinput__content-input {
			color: v-bind('themeStyles.textPrimary') !important;
			font-size: 28rpx !important;

			&::placeholder {
				color: v-bind('themeStyles.textPlaceholder') !important;
			}
		}
	}

	/**
	 * 复选框样式
	 */
	:deep(.custom-checkbox) {
		.checklist-group {
			display: flex;
			gap: 16rpx;
		}

		.checklist-box {
			flex: 1;
			padding: 16rpx 20rpx;
			background: v-bind('themeStyles.bgCard');
			border: 2rpx solid v-bind('themeStyles.borderLight');
			border-radius: 12rpx;
			text-align: center;
			transition: all 0.3s ease;

			&.is--checked {
				background: v-bind('themeStyles.primaryGradient');
				border-color: v-bind('themeStyles.primaryColor');
				color: white;
				box-shadow: v-bind('themeStyles.activeShadow');
				transform: translateY(-2rpx);
			}
		}

		.checklist-text {
			font-size: 26rpx;
			font-weight: 500;
		}
	}

	/**
	 * 数字输入框样式
	 */
	:deep(.custom-number-box) {
		.uni-numbox {
			background: transparent !important;
		}

		.uni-numbox__value {
			color: v-bind('themeStyles.textPrimary') !important;
			font-size: 28rpx !important;
			font-weight: 600 !important;
		}

		.uni-numbox__minus,
		.uni-numbox__plus {
			background: v-bind('themeStyles.primaryGradient') !important;
			color: white !important;
			border: none !important;
			border-radius: 8rpx !important;
			font-size: 32rpx !important;

			&:active {
				opacity: 0.8;
			}
		}
	}

	/**
	 * 按钮区域
	 */
	.task-popup-footer {
		display: flex;
		gap: 16rpx;
		margin-top: 40rpx;
		padding-top: 32rpx;
		border-top: 1rpx solid v-bind('themeStyles.borderLight');
	}

	.task-cancel-button,
	.task-confirm-button {
		flex: 1;
		height: 88rpx;
		border-radius: 16rpx;
		font-size: 28rpx;
		font-weight: 600;
		border: none;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		position: relative;
		overflow: hidden;

		&::before {
			content: '';
			position: absolute;
			top: 50%;
			left: 50%;
			width: 0;
			height: 0;
			border-radius: 50%;
			background: rgba(255, 255, 255, 0.3);
			transform: translate(-50%, -50%);
			transition: width 0.6s, height 0.6s;
		}

		&:active::before {
			width: 200%;
			height: 200%;
		}
	}

	.task-cancel-button {
		background: v-bind('themeStyles.bgSecondary');
		border: 2rpx solid v-bind('themeStyles.borderLight');

		.button-text {
			color: v-bind('themeStyles.textSecondary');
		}

		&:active {
			transform: scale(0.96);
			background: v-bind('themeStyles.accentBg');
		}
	}

	.task-confirm-button {
		background: v-bind('themeStyles.primaryGradient');
		box-shadow: v-bind('themeStyles.buttonBoxShadow');

		.button-text {
			color: white;
		}

		&:active {
			transform: scale(0.96);
			box-shadow: v-bind('themeStyles.shadowSm');
		}
	}

	.button-text {
		font-size: 28rpx;
		font-weight: 600;
		position: relative;
		z-index: 1;
	}

	/**
	 * 弹窗始终居中并覆盖视口（不随页面滚动）
	 */
	:deep(.uni-popup__wrapper) {
		position: fixed !important;
		top: 0 !important;
		left: 0 !important;
		right: 0 !important;
		bottom: 0 !important;
		z-index: 1000 !important;
		display: flex !important;
		align-items: center !important;
		justify-content: center !important;
		background: rgba(0, 0, 0, 0.5) !important;
		backdrop-filter: blur(4px);
	}

	:deep(.uni-popup__wrapper-box) {
		pointer-events: auto;
	}
</style>

